<template>
	<view class="region-agent">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 主要内容 -->
		<view v-else>
			<!-- 代理状态卡片 -->
		<view class="agent-status-card">
			<view class="status-header">
				<view class="status-title">代理状态</view>
				<view class="status-badge" :class="agentStatus.class">
					{{ agentStatus.text }}
				</view>
			</view>
			<view class="status-content" v-if="agentInfo">
				<view class="info-row">
					<text class="label">代理类型：</text>
					<text class="value">{{ agentInfo.agent_type_text }}</text>
				</view>
				<view class="info-row">
					<text class="label">代理区域：</text>
					<text class="value">{{ agentInfo.region_text }}</text>
				</view>
				<view class="info-row">
					<text class="label">佣金比例：</text>
					<text class="value">{{ (Number(agentInfo.commission_rate) * 100).toFixed(2) }}%</text>
				</view>
				<view class="info-row">
					<text class="label">加入时间：</text>
					<text class="value">{{ agentInfo.create_time_text }}</text>
				</view>
			</view>
		</view>

		<!-- 收益统计 -->
		<view class="income-stats" v-if="agentInfo">
			<view class="stats-title">收益统计</view>
			<view class="stats-grid">
				<view class="stats-item">
					<view class="stats-value">{{ incomeStats.total_amount }}</view>
					<view class="stats-label">总收益</view>
				</view>
				<view class="stats-item">
					<view class="stats-value">{{ incomeStats.settled_amount }}</view>
					<view class="stats-label">已结算</view>
				</view>
				<view class="stats-item">
					<view class="stats-value">{{ incomeStats.pending_amount }}</view>
					<view class="stats-label">待结算</view>
				</view>
			</view>
		</view>

		<!-- 申请状态卡片 -->
		<view class="apply-status-card" v-if="applyInfo && !agentInfo">
			<view class="status-header">
				<view class="status-title">申请状态</view>
				<view class="status-badge" :class="agentStatus.class">
					{{ agentStatus.text }}
				</view>
			</view>
			<view class="status-content">
				<view class="info-row">
					<text class="label">申请类型：</text>
					<text class="value">{{ applyInfo.agent_type_text }}</text>
				</view>
				<view class="info-row">
					<text class="label">申请区域：</text>
					<text class="value">{{ applyInfo.region_text }}</text>
				</view>
				<view class="info-row">
					<text class="label">申请理由：</text>
					<text class="value">{{ applyInfo.apply_reason }}</text>
				</view>
				<view class="info-row">
					<text class="label">申请时间：</text>
					<text class="value">{{ applyInfo.create_time_text }}</text>
				</view>
				<view class="info-row" v-if="applyInfo.review_status === '2' && applyInfo.reject_reason">
					<text class="label">拒绝理由：</text>
					<text class="value reject-reason">{{ applyInfo.reject_reason }}</text>
				</view>
			</view>
		</view>

		<!-- 申请代理表单 -->
		<view class="apply-form" v-if="!agentInfo && !applyInfo">
			<view class="form-title">申请区域代理</view>
			<view class="form-content">
				<view class="form-item">
					<view class="form-label">代理类型</view>
					<picker mode="selector" @change="onAgentTypeChange" :value="applyForm.agent_type_index" :range="getAvailableAgentTypes()">
						<view class="picker-text">{{ getAvailableAgentTypes()[applyForm.agent_type_index] }}</view>
					</picker>
				</view>
				<view class="form-item">
					<view class="form-label">代理区域</view>
					<view class="picker-text" @click="showAddressPicker">
						{{ getSelectedRegionText() || getRegionPlaceholder() }}
					</view>
				</view>
				
				<!-- 文件上传 -->
				<view class="form-item">
					<view class="form-label">相关文件</view>
					<view class="upload-container">
						<!-- 上传按钮 -->
						<view class="upload-btn" @click="chooseFiles">
							
							<text class="upload-text">上传文件</text>
						</view>
						
						<!-- 文件列表 -->
						<view class="file-list" v-if="uploadedFiles.length > 0">
							<view class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
								<!-- 图片预览 -->
								<image 
									v-if="file.type === 'image'" 
									:src="file.url" 
									class="file-preview" 
									@click="previewImage(file.url)">
								</image>
								<!-- 视频预览 -->
								<video 
									v-else-if="file.type === 'video'" 
									:src="file.url" 
									class="file-preview video-preview"
									:poster="getVideoPoster(file.url)"
									@click="previewVideo(file.url)">
								</video>
								<!-- 文档图标 -->
								<view 
									v-else 
									class="file-preview document-preview"
									@click="previewDocument(file.url)">
									<image src="/static/img/icon_wenti.png" class="document-icon"></image>
								</view>
								
								<view class="file-info">
									<text class="file-name">{{ file.name }}</text>
									<text class="file-size">{{ file.size }}</text>
									<text class="file-type">{{ getFileTypeText(file.type) }}</text>
								</view>
								<view class="file-actions">
									<text class="action-btn delete" @click="removeFile(index)">删除</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="form-item">
					<view class="form-label">申请理由</view>
					<textarea 
						v-model="applyForm.reason" 
						placeholder="请填写申请理由"
						class="form-textarea"
						maxlength="200"
					></textarea>
				</view>
				<view class="form-actions">
					<button class="btn-submit" @click="submitApply">提交申请</button>
				</view>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="function-menu">
			<view class="menu-item" @click="goToCommission" v-if="agentInfo">
				<image src="/static/img/icon_shouhou.png" class="menu-icon"></image>
				<view class="menu-text">佣金记录</view>
				<image src="/static/img/icon_jiantou_18.png" class="menu-arrow"></image>
			</view>
			<view class="menu-item" @click="goToRules">
				<image src="/static/img/icon_wenti.png" class="menu-icon"></image>
				<view class="menu-text">代理规则</view>
				<image src="/static/img/icon_jiantou_18.png" class="menu-arrow"></image>
			</view>
		</view>

		<!-- 地址选择弹窗 -->
		<region-address-picker 
			v-if="showAddressModal" 
			:showPop="showAddressModal" 
			:maxLevel="getMaxLevel()"
			@confirm_shop="onAddressConfirm" 
			@cancel="onAddressCancel">
		</region-address-picker>

		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, defineAsyncComponent, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { upload, ApitestUrl, getAgentInfo, getApplyStatus, checkRegionConflict, submitAgentApply } from '@/utils/api'

// 使用专门的区域地址选择组件
const RegionAddressPicker = defineAsyncComponent(() => import('@/components/region-address-picker/region-address-picker.vue'))

// 定义类型接口
interface AgentInfo {
	status: string
	agent_type_text: string
	region_text: string
	commission_rate: string
	create_time_text: string
}

interface ApplyForm {
	agent_type_index: number
	region_index: number
	reason: string
}

interface UploadedFile {
	url: string
	name: string
	size: string
	type: string // 文件类型：image, video, document
}

// 响应式数据
const loading = ref(true) // 加载状态
const agentInfo = ref<AgentInfo | null>(null)
const applyInfo = ref<any>(null) // 申请信息
const incomeStats = ref({
	total_amount: '0.00',
	settled_amount: '0.00',
	pending_amount: '0.00'
})
const applyForm = ref<ApplyForm>({
	agent_type_index: 0,
	region_index: 0,
	reason: ''
})

// 上传的文件列表
const uploadedFiles = ref<UploadedFile[]>([])

// 地址选择相关
const showAddressModal = ref(false)
const selectedRegion = ref<string[]>([])
const selectedRegionIds = ref<number[]>([])

// 代理类型选项
const agentTypeOptions = ref(['省级代理', '市级代理', '区级代理'])

// 直辖市列表
const municipalities = ['北京市', '天津市', '上海市', '重庆市']

// 计算属性
const agentStatus = computed(() => {
	// 如果已是代理，显示代理状态
	if (agentInfo.value) {
		return {
			text: '已通过',
			class: 'status-approved'
		}
	}
	
	// 如果有申请记录，显示申请状态
	if (applyInfo.value) {
		switch (String(applyInfo.value.review_status)) {
			case '0':
				return {
					text: '待审核',
					class: 'status-pending'
				}
			case '1':
				return {
					text: '已通过',
					class: 'status-approved'
				}
			case '2':
				return {
					text: '已拒绝',
					class: 'status-rejected'
				}
			default:
				return {
					text: '未知状态',
					class: 'status-pending'
				}
		}
	}
	
	// 没有任何记录
	return {
		text: '未申请',
		class: 'status-pending'
	}
})

// 生命周期
onLoad(async () => {
	loading.value = true
	try {
		await Promise.all([
			loadAgentInfo(),
			loadApplyStatus(),
			loadIncomeStats()
		])
	} finally {
		loading.value = false
	}
})

// 组件卸载时清理
onUnmounted(() => {
	showAddressModal.value = false
})

// 方法
const loadAgentInfo = async () => {
	try {
		const res: any = await getAgentInfo()
		if (res.code === 1) {
			agentInfo.value = res.data.agent_info
			incomeStats.value = res.data.income_stats
		}
	} catch (error) {
		console.error('加载代理信息失败:', error)
	}
}

const loadApplyStatus = async () => {
	try {
		const res: any = await getApplyStatus()
		if (res.code === 1) {
			applyInfo.value = res.data.apply_info
		}
	} catch (error) {
		console.error('加载申请状态失败:', error)
	}
}

const loadIncomeStats = async () => {
	// 收益统计已经在loadAgentInfo中一起获取了
}


const goToCommission = () => {
	uni.navigateTo({
		url: '/mypages/region/commission/commission'
	})
}

const goToTeam = () => {
	uni.navigateTo({
		url: '/mypages/region/team/team'
	})
}

const goToRules = () => {
	uni.navigateTo({
		url: '/mypages/region/rules/rules'
	})
}


const onAgentTypeChange = (e: any) => {
	applyForm.value.agent_type_index = e.detail.value
	// 代理类型变化时清空已选择的区域
	selectedRegion.value = []
	selectedRegionIds.value = []
}

// 获取可用的代理类型选项
const getAvailableAgentTypes = () => {
	// 如果已经选择了区域，检查是否为直辖市
	if (selectedRegion.value && selectedRegion.value.length > 0) {
		const province = selectedRegion.value[0]
		if (municipalities.includes(province)) {
			// 直辖市只能选择省级代理
			return ['省级代理']
		}
	}
	// 其他情况显示所有选项
	return ['省级代理', '市级代理', '区级代理']
}

// 获取区域选择提示文本
const getRegionPlaceholder = () => {
	const agentType = applyForm.value.agent_type_index
	if (agentType === 0) {
		return '请选择省份'
	} else if (agentType === 1) {
		return '请选择省市区'
	} else {
		return '请选择省市区'
	}
}

// 获取已选择的区域文本
const getSelectedRegionText = () => {
	if (!selectedRegion.value || !Array.isArray(selectedRegion.value)) {
		return ''
	}
	
	const agentType = applyForm.value.agent_type_index
	const [province, city, area] = selectedRegion.value
	
	if (agentType === 0) {
		// 省级代理：只显示省份
		return province
	} else if (agentType === 1) {
		// 市级代理：显示省+市
		return [province, city].filter(Boolean).join(' ')
	} else {
		// 区级代理：显示省+市+区
		return [province, city, area].filter(Boolean).join(' ')
	}
}

// 获取最大选择级别
const getMaxLevel = () => {
	const agentType = applyForm.value.agent_type_index
	if (agentType === 0) {
		return 1 // 省级代理只能选到省级
	} else if (agentType === 1) {
		return 2 // 市级代理只能选到市级
	} else {
		return 3 // 区级代理可以选到区级
	}
}

// 显示地址选择器
const showAddressPicker = async () => {
	await nextTick()
	showAddressModal.value = true
}

// 地址选择确认
const onAddressConfirm = (regionStr: string, regionIds: number[]) => {
	try {
		console.log('地址选择确认:', { regionStr, regionIds, agentType: applyForm.value.agent_type_index })
		
		const agentType = applyForm.value.agent_type_index
		let province = ''
		let city = ''
		let area = ''

		// 处理不同的分隔符：可能是空格、斜杠、或其他分隔符
		let parts: string[] = []
		if (regionStr.includes('/')) {
			parts = regionStr.split('/').filter(p => p.trim() !== '')
		} else if (regionStr.includes(' ')) {
			parts = regionStr.split(' ').filter(p => p.trim() !== '')
		} else {
			parts = [regionStr]
		}

		if (parts.length === 1) {
			// Case: "北京市" or "河北省"
			province = parts[0].trim()
			if (agentType === 1 || agentType === 2) {
				// 如果是市级或区级代理，且只有一个部分，可能是直辖市
				city = parts[0].trim()
			}
		} else if (parts.length === 2) {
			// Case: "河北省 石家庄市" or "河北省/石家庄市"
			province = parts[0].trim()
			city = parts[1].trim()
		} else if (parts.length >= 3) {
			// Case: "河北省 石家庄市 桥西区" or "河北省/石家庄市/长安区"
			province = parts[0].trim()
			city = parts[1].trim()
			area = parts[2].trim()
		}

		// 检查是否为直辖市
		if (municipalities.includes(province)) {
			// 直辖市只能做省级代理
			applyForm.value.agent_type_index = 0
			selectedRegion.value = [province, '', '']
		} else {
			// 根据代理类型决定保存哪些字段
			if (agentType === 0) { // 省级代理
				selectedRegion.value = [province, '', '']
			} else if (agentType === 1) { // 市级代理
				selectedRegion.value = [province, city, '']
			} else { // 区级代理
				selectedRegion.value = [province, city, area]
			}
		}
		
		selectedRegionIds.value = regionIds
		showAddressModal.value = false
		
		// 检查区域冲突
		checkRegionConflictAsync()
	} catch (error) {
		console.error('地址选择确认错误:', error)
		showAddressModal.value = false
	}
}

// 地址选择取消
const onAddressCancel = () => {
	showAddressModal.value = false
}

// 检查区域冲突
const checkRegionConflictAsync = async () => {
	try {
		const agentType = applyForm.value.agent_type_index === 0 ? 'province_agent' : 
						  applyForm.value.agent_type_index === 1 ? 'city_agent' : 'area_agent'
		
		const checkData = {
			agent_type: agentType,
			province: selectedRegion.value[0] || '',
			city: selectedRegion.value[1] || '',
			area: selectedRegion.value[2] || ''
		}
		
		const res: any = await checkRegionConflict(checkData)
		if (res.code === 0) {
			// 有冲突，显示错误信息
			uni.showModal({
				title: '区域冲突',
				content: res.msg,
				showCancel: false,
				confirmText: '重新选择',
				success: () => {
					// 清空已选择的区域，让用户重新选择
					selectedRegion.value = []
					selectedRegionIds.value = []
				}
			})
		}
		// 如果没有冲突，不显示任何提示，让用户继续操作
	} catch (error) {
		console.error('检查区域冲突失败:', error)
	}
}

// 文件上传相关方法
const chooseFiles = () => {
	uni.showActionSheet({
		itemList: ['选择图片', '选择视频', '选择文件'],
		success: (res) => {
			if (res.tapIndex === 0) {
				// 选择图片
				chooseImages()
			} else if (res.tapIndex === 1) {
				// 选择视频
				chooseVideos()
			} else if (res.tapIndex === 2) {
				// 选择文件
				chooseDocuments()
			}
		}
	})
}

// 选择图片
const chooseImages = () => {
	uni.chooseImage({
		count: 9, // 最多选择9张图片
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			uploadFiles(res.tempFilePaths as string[], 'image')
		},
		fail: (error: any) => {
			console.log('选择图片失败:', error)
		}
	})
}

// 选择视频
const chooseVideos = () => {
	uni.chooseVideo({
		sourceType: ['album', 'camera'],
		maxDuration: 60, // 最长60秒
		camera: 'back',
		success: (res) => {
			uploadFiles([res.tempFilePath], 'video')
		},
		fail: (error: any) => {
			console.log('选择视频失败:', error)
		}
	})
}

// 选择文档
const chooseDocuments = () => {
	// 使用 uni.chooseFile 选择文档（H5端）
	// 小程序端需要使用其他方式
	// #ifdef H5
	uni.chooseFile({
		count: 9,
		type: 'all',
		success: (res) => {
			uploadFiles(res.tempFilePaths as string[], 'document')
		},
		fail: (error: any) => {
			console.log('选择文件失败:', error)
		}
	})
	// #endif
	
	// #ifndef H5
	// 小程序端暂时只支持图片和视频
	uni.showToast({
		title: '小程序端暂不支持文档上传',
		icon: 'none'
	})
	// #endif
}

// 批量上传文件
const uploadFiles = (filePaths: string[], fileType: string = 'image') => {
	let uploadCount = 0
	const totalCount = filePaths.length
	
	uni.showLoading({
		title: `上传中 ${uploadCount}/${totalCount}`,
		mask: true
	})
	
	filePaths.forEach((filePath, index) => {
		// 获取文件信息
		const fileName = getFileName(filePath, fileType, index + 1)
		const fileSize = getFileSize(filePath)
		
		uni.uploadFile({
			url: upload,
			filePath: filePath,
			name: 'file',
			header: {
				'ba-user-token': uni.getStorageSync('token'),
				'server': 1,
			},
			success: (uploadFileRes: any) => {
				uploadCount++
				const result = JSON.parse(uploadFileRes.data)
				
				if (result.code === 1) {
					const fileUrl = result.data.file.url
					let fullFileUrl = fileUrl
					if (fileUrl && !fileUrl.startsWith('http')) {
						fullFileUrl = ApitestUrl.replace('/api', '') + fileUrl
					}
					
					// 添加到文件列表
					uploadedFiles.value.push({
						url: fullFileUrl,
						name: fileName,
						size: fileSize,
						type: fileType
					})
					
					// 更新加载提示
					uni.showLoading({
						title: `上传中 ${uploadCount}/${totalCount}`,
						mask: true
					})
					
					// 所有文件上传完成
					if (uploadCount === totalCount) {
						uni.hideLoading()
						uni.showToast({
							title: '上传完成',
							icon: 'success'
						})
					}
				} else {
					uploadCount++
					if (uploadCount === totalCount) {
						uni.hideLoading()
					}
					uni.showToast({
						title: '部分文件上传失败',
						icon: 'none'
					})
				}
			},
			fail: (error: any) => {
				uploadCount++
				if (uploadCount === totalCount) {
					uni.hideLoading()
				}
				console.error('上传失败:', error)
			}
		})
	})
}

// 获取文件名
const getFileName = (filePath: string, fileType: string, index: number) => {
	const timestamp = new Date().getTime()
	const shortTime = timestamp.toString().slice(-6) // 只取后6位时间戳
	
	if (fileType === 'image') {
		return `图片${index}_${shortTime}.jpg`
	} else if (fileType === 'video') {
		return `视频${index}_${shortTime}.mp4`
	} else if (fileType === 'document') {
		// 从文件路径获取扩展名
		const ext = filePath.split('.').pop() || 'file'
		return `文档${index}_${shortTime}.${ext}`
	}
	return `文件${index}_${shortTime}`
}

// 获取文件大小
const getFileSize = (filePath: string) => {
	// 这里可以获取实际文件大小，暂时返回占位符
	return '已上传'
}

// 删除文件
const removeFile = (index: number) => {
	uploadedFiles.value.splice(index, 1)
}

// 预览图片
const previewImage = (url: string) => {
	uni.previewImage({
		urls: [url],
		current: url
	})
}

// 预览视频
const previewVideo = (url: string) => {
	// 使用 uni.createVideoContext 或其他方式预览视频
	// 这里暂时使用图片预览的方式
	uni.previewImage({
		urls: [url],
		current: url
	})
}

// 预览文档
const previewDocument = (url: string) => {
	// 打开文档链接
	// #ifdef H5
	window.open(url, '_blank')
	// #endif
	
	// #ifndef H5
	uni.showToast({
		title: '请复制链接在浏览器中打开',
		icon: 'none'
	})
	// 复制链接到剪贴板
	uni.setClipboardData({
		data: url,
		success: () => {
			uni.showToast({
				title: '链接已复制',
				icon: 'success'
			})
		}
	})
	// #endif
}

// 获取视频封面
const getVideoPoster = (url: string) => {
	// 这里可以生成视频封面，暂时返回空
	return ''
}

// 获取文件类型文本
const getFileTypeText = (type: string) => {
	switch (type) {
		case 'image':
			return '图片'
		case 'video':
			return '视频'
		case 'document':
			return '文档'
		default:
			return '文件'
	}
}

const submitApply = async () => {
	if (!applyForm.value.reason.trim()) {
		uni.showToast({
			title: '请填写申请理由',
			icon: 'none'
		})
		return
	}
	
	if (!selectedRegion.value || selectedRegion.value.length === 0 || !selectedRegion.value[0]) {
		const agentType = applyForm.value.agent_type_index
		let message = '请选择代理区域'
		if (agentType === 0) {
			message = '请选择省份'
		} else if (agentType === 1) {
			message = '请选择省市区'
		}
		uni.showToast({
			title: message,
			icon: 'none'
		})
		return
	}

	// 文件验证（可选）
	if (uploadedFiles.value.length === 0) {
		uni.showModal({
			title: '提示',
			content: '是否不上传任何文件？',
			success: (res) => {
				if (res.confirm) {
					submitApplication()
				}
			}
		})
		return
	}
	
	submitApplication()
}

// 提交申请的具体逻辑
const submitApplication = async () => {
	try {
		// 准备申请数据
		const applyData = {
			agent_type: applyForm.value.agent_type_index === 0 ? 'province_agent' : 
						applyForm.value.agent_type_index === 1 ? 'city_agent' : 'area_agent',
			province: selectedRegion.value[0] || '',
			city: selectedRegion.value[1] || '',
			area: selectedRegion.value[2] || '',
			reason: applyForm.value.reason,
			files: uploadedFiles.value.map(file => file.url).join(',') // 上传的文件URL数组，用逗号分隔
		}
		
		console.log('提交申请数据:', applyData)
		
		// 调用API提交申请
		const res: any = await submitAgentApply(applyData)
		if (res.code === 1) {
			uni.showToast({
				title: res.msg || '申请提交成功',
				icon: 'success'
			})
			// 重新加载代理信息和申请状态
			loadAgentInfo()
			loadApplyStatus()
		} else {
			uni.showToast({
				title: res.msg || '申请提交失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('申请提交失败:', error)
		uni.showToast({
			title: '申请提交失败',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss" scoped>
@import './agent.scss';
</style>
